package dat255.calendarclock.controller;

import java.util.GregorianCalendar;
import java.util.Observable;
import java.util.Observer;

import android.app.Activity;
import android.gesture.Gesture;
import android.gesture.GestureOverlayView;
import android.gesture.GestureStroke;
import android.graphics.Color;
import android.os.Bundle;
import dat255.calendarclock.R;
import dat255.calendarclock.model.event.EventHandler;
import dat255.calendarclock.view.ClockCalendarView;

public class ClockCalendarController extends Activity implements Observer {

	private ClockCalendarView clockView;
	private static float GESTURE_NAME_SCALE = 2/5f;
	private GestureOverlayView.OnGesturePerformedListener gestureListener = new GestureOverlayView.OnGesturePerformedListener() {

		@Override
		public void onGesturePerformed(GestureOverlayView overlay,
				Gesture gesture) {
			
			for (GestureStroke stroke : gesture.getStrokes()) {
				if (stroke.points.length < 25
						& stroke.length > GESTURE_NAME_SCALE
								* findViewById(R.id.ClockCalendarLayout)
										.getWidth()) {
					float deltaX = stroke.points[0] - stroke.points[stroke.points.length - 1];
					int dayDelta = (int) (deltaX / Math.abs(deltaX));

					EventHandler eventHandler = EventHandler.getInstance();
					
					GregorianCalendar selectedDay = eventHandler.getSelectedDay();
					selectedDay.add(GregorianCalendar.DATE, dayDelta);
					eventHandler.setSelectedDay(selectedDay);
				}
			}
			
			

		}
	};
	
	// System state

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.clockview_layout);
		SecondTimer.getInstance().addObserver(this);
		EventHandler.getInstance().addObserver(this);
		
		// Assign a gesture detector
		GestureOverlayView gestureOverlay = (GestureOverlayView) findViewById(R.id.ClockCalendarViewGestureOverlay);
		gestureOverlay.addOnGesturePerformedListener(gestureListener);
		gestureOverlay.setGestureColor(Color.TRANSPARENT);
		gestureOverlay.setUncertainGestureColor(Color.TRANSPARENT);
				
		clockView = (ClockCalendarView) findViewById(R.id.ClockCalendarView);
	}

	@Override
	protected void onResume() {
		update(null, null);
		super.onResume();
	}
	
	
	@Override
	public void update(Observable observable, Object data) {
		if(observable instanceof SecondTimer) {
			clockView.invalidate();
		}
		if(observable instanceof EventHandler){
			clockView.loadEvents();
		}
		
	}

}
